﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using Dimok.Exceptions;
using Data.LINQ;
namespace WSA {
	[WebService(Namespace = "http://motobankcorp.com/uploads")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	[System.Web.Script.Services.ScriptService]
	public class Uploads : Common {
		[WebMethod]
		public v_Upload ImportUpload(int UploadID, int PurchaseBatchID) {
			var mb = new MotoBank();
			try {
					var up = new v_Upload_Process() { UploadID = UploadID, PurchaseBatchID = PurchaseBatchID };
					mb.v_Upload_Processes.InsertOnSubmit(up);
					mb.SubmitChanges();
					return mb.v_Uploads.Single(r => r.ID == UploadID);
			} catch (Exception exc) { ASPException.Publish(exc); throw exc; }
			//throw new Exception("UploadIDs:" + Jayrock.Json.Conversion.JsonConvert.ExportToString(UploadIDs)+",BatchID:"+PurchaseBatchID);
		}
		[WebMethod]
		public v_Upload GetUploadCarPrice(int UploadID, int BookValueTypeID) {
			try {
				var mb = new MotoBank();
				var bp_vt = mb.ts_CarBookProvider_ValueTypes.Single(r => r.ID == BookValueTypeID);
				var uploads = mb.v_Uploads.Single(r => r.ID == UploadID);
				var cp = Lib.GetCarPrice(uploads.Serial_, 0, uploads.St,uploads.Make+" "+uploads.Model+"", BookValueTypeID);
				if (cp.Price == 0) throw new Exception("No price for " + uploads);
				var u = mb.t_Uploads.Single(r => r.ID == UploadID);
				u.BookValue = cp.Price;
				u.BookValueTypeID = cp.TypeID;
				mb.SubmitChanges();
				return new MotoBank().v_Uploads.Single(r => r.ID == UploadID);
			} catch (Exception exc) { ASPException.Publish(exc); throw exc; }
		}
		[WebMethod]
		public object ClearUploadAccounts(int BatchID) {
			try{
				new MotoBank().t_Uploads.Delete(u => u.UploadInfoID == BatchID);
				return new MotoBank().v_UploadInfos.Where(ui => ui.ID == BatchID).Single();
			} catch (Exception exc) { ASPException.Publish(exc); throw exc; }
		}
		class PQ_Info {

		}
		[WebMethod]
		public v_UploadDecision DecisionUpload(int ProgramID, int ID) {
			try {
				var mb = new MotoBank();
				var ret = mb.ExecuteQuery<v_UploadDecision>("EXEC s_PQ_Info {0},{1}",ProgramID, ID).SingleOrDefault();
				if (ret == null) throw new Exception("Upload " + ID + " does not belong to any rule.");
				var u = mb.t_Uploads.Where(a => a.ID == ID).Single();
				var ud = u.t_UploadDecision;
				if (ud == null) ud = u.t_UploadDecision = new t_UploadDecision();
				ud.Tier = ret.Tier; ud.Price = ret.Price; ud.ProgramID = ret.ProgramID;
				mb.SubmitChanges();
				return ret;
			} catch (Exception exc) {
				exc.Data["UploadID"] = ID;
				ASPException.Publish(exc); throw exc; 
			}
		}
	}
}